﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Globalization;
using LogLib;

namespace NewCapturerDemo.DSLR
{
    internal class DirConfig
    {
        /// <summary>
        /// 错误信息
        /// </summary>
        private static string strErrorMessage = "";
        public static string ErrorMessage
        {
            get { return strErrorMessage; }
        }

        /// <summary>
        /// 系统日志文件保存路径
        /// </summary>
        private static string IniFileName;

        public static readonly string ConfigFileName = "CamParas.ini";

        /// <summary>
        /// 系统日志文件保存路径
        /// </summary>
        private static string _baseDirectory = "D:\\KPhoto";
        public static string BaseDirectory
        {
            get { return _baseDirectory; }
        }

        protected static IFormatProvider ifp = new CultureInfo("zh-CN", true);

        /// <summary>
        /// 当前日期
        /// </summary>
        private static DateTime _nowDate = DateTime.MinValue;

        private static TimeZoneInfo localZoneInfo = null;

        /// <summary>
        /// 同步写锁
        /// </summary>
        private static object lockflag = new object();

        /// <summary>
        /// 当前的默认日记保存目录
        /// </summary>
        private static string _todayDirectory = "";
        public static string TodayDirectory
        {
            get
            {
                lock (lockflag)
                {
                    CheckFolder();
                    return _todayDirectory;
                }
            }
        }

        public static DateTime Now()
        {         
            return TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, localZoneInfo);
        }

        static DirConfig()
        {
            string id = "China Standard Time";
            localZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(id);
            CheckIniFile();           
            _nowDate = Now().Date;
        }

        public static void SaveBaseDirectory(string path)
        {
            WriteValue("Download", "Dir", path, IniFileName);
        }

        private static void CheckAndSetDiskName(ref string path)
        {
            bool available = false;
            path = path.Trim();
            string diskName = path.Substring(0, 1);
            diskName = diskName.ToUpper();
            DriveInfo[] allDirves = DriveInfo.GetDrives();
            for (int i = 0; i < allDirves.Length; i++)
            {
                string name = allDirves[i].Name.Substring(0, 1);
                if (diskName.Equals(name.ToUpper()))
                {
                    if (allDirves[i].IsReady)
                    {
                        available = true;
                        break;
                    }
                }
            }
            if (!available)
            {
                for (int i = 0; i < allDirves.Length; i++)
                {
                    if (allDirves[i].IsReady)
                    {
                        path = allDirves[i].Name + "DCIM\\";
                        WriteValue("Download", "Dir", path, IniFileName);
                        break;
                    }
                }
            }
        }

        public static bool LoadConfig()
        {
            CheckIniFile();
            string path = IniValue("Download", "Dir");
            if (string.IsNullOrEmpty(path))
            {
                path = _baseDirectory;
            }
            CheckAndSetDiskName(ref path);
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception ex)
                {
                    strErrorMessage = string.Format("试图创建目录{0}失败，原因: {1}.\n请检查配置文件{2}的配置是否正确.", path, ex.Message, IniFileName);
                    return false;
                }
            }
            _baseDirectory = path;
            CheckFolder();
            return true;
        }

        private static void CheckIniFile()
        {
            IniFileName = Path.Combine(Application.StartupPath, ConfigFileName);
            if (!File.Exists(IniFileName))
            {
                WriteValue("Download", "Dir", _baseDirectory, IniFileName);
            }
        }

        /// <summary>
        /// 检查当天的文件夹是否创建
        /// </summary>
        public static void CheckFolder()
        {
            DateTime currentTime = Now();
            if (!_nowDate.Equals(currentTime.Date) || string.IsNullOrEmpty(_todayDirectory))
            {
                _nowDate = currentTime.Date;
                _todayDirectory = string.Format(@"{0}\{1}\{2}",
                    _baseDirectory, currentTime.ToString("yyyyMM", ifp),
                    currentTime.ToString("dd", ifp));
            }
            if (!Directory.Exists(_todayDirectory))
            {
                Directory.CreateDirectory(_todayDirectory);
                Log.WriteAsync($"创建了目录：{_todayDirectory}");
            }
        }

        #region 读取INI文件
        /// <summary>
        /// 读取INI文件
        /// </summary>
        /// <param name="Section">段落</param>
        /// <param name="IniKey">关键字</param>
        /// <returns></returns>
        public static string IniValue(string Section, string IniKey)
        {
            StringBuilder temp = new StringBuilder(500);
            int i = GetPrivateProfileString(Section, IniKey, "", temp, 500, IniFileName);
            return temp.ToString();
        }

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        #endregion

        #region 写INI文件
        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="Section">段落</param>
        /// <param name="IniKey">关键字</param>
        /// <returns></returns>
        public static long WriteValue(string Section, string IniKey, string NewValue, string iniFileName)
        {
            long i = WritePrivateProfileString(Section, IniKey, NewValue, iniFileName);
            return i;
        }

        [DllImport("kernel32")]
        public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        #endregion
    }
}
